/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        return recur(root)==-1?false:true;
    }

    int recur(TreeNode* root)
    {
        if(root==nullptr)return 0;//后序：左右根，从底向顶
        int left=recur(root->left);
        if(left==-1)return -1;//剪枝
        int right=recur(root->right);
        if(right==-1)return -1;//剪枝

        return abs(left-right)<2?max(left,right)+1:-1;

    }
};